using System;
using System.Security.Principal;


namespace PhilWicklund.com.PollingWebPart.Utilities
{
    public class RevertToAppPool
    {
        private WindowsImpersonationContext ctx = null;

        //Revert to the original application pool security context
        //We only want to do this if we are not already running as the system
        public void UseAppPoolIdentity()
        {
            try
            {
                if (!WindowsIdentity.GetCurrent().IsSystem)
                {
                    ctx = WindowsIdentity.Impersonate(System.IntPtr.Zero);
                }
            }
            catch { }
        }

        //Return to impersonating the authenticated user
        //Anonymous users are impersonated as IUSR_machinename, by default
        public void ReturnToImpersonatingCurrentUser()
        {
            try
            {
                if (ctx != null)
                {
                    ctx.Undo();
                }
            }
            catch { }
        }
    }
}